package de.baumann.browser.present

import de.baumann.browser.api.OdinObserver
import de.baumann.browser.api.net.vo.*
import de.baumann.browser.iview.IMineView.Companion.SUPER_NODE_USER
import de.baumann.browser.iview.IMiningView
import de.baumann.browser.model.*
import de.baumann.browser.utils.*


class MiningPresenterNew : NoticePresenter<IMiningView>() {

    private var miningModel = MiningModel()
    private var userModel = UserModel()

    fun getOdinOre() {
        if (!isLogined() || getLicence().isEmpty()) {
            view.setOdinOre(null)
            return
        }

        this.miningModel.getOdinOres(getLicence())
                .subscribe(object : OdinObserver<List<OdinOre>>() {
                    override fun onSuccess(data: List<OdinOre>?) {
                        if (view != null)
                            view.setOdinOre(data)
                    }
                })
    }

    fun getOdinAndHashValue() {
        this.userModel.odinAndHashValue
                .subscribe(object : OdinObserver<OdinAndHashValue>(view, false) {
                    override fun onSuccess(data: OdinAndHashValue?) {
                        if (view != null && data != null) {
                            view.setTotalHash(data.totalHash)
                        }
                    }
                })
    }

    /**
     * 采集ODIN
     */
    fun gatherOre(odinOre: OdinOre) {
        this.miningModel.gatherOre(odinOre)
                .subscribe(object : OdinObserver<Any>() {
                    override fun onSuccess(data: Any?) {
                    }
                })
    }

    fun getAirDropTime() {
        AppConfigModel()
                .getAirDropTime()
                .subscribe(object : OdinObserver<String>() {
                    override fun onSuccess(data: String?) {
                        if (view != null && data != null) {
                            view.setTime(data.toLong())
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (view != null) {
                            view.setTime(TimeUtil.nextDay())
                        }
                    }
                })
    }

    fun login() {
        userModel.login(getMoneyAddress(), "")
                .subscribe(object : OdinObserver<LoginInfo>(view) {
                    override fun onSuccess(loginInfo: LoginInfo) {
                        saveUser(loginInfo)
                        UnicornUtil.setUserInfo(loginInfo)
                        saveInviteCode(loginInfo.inviteCode)
                        saveInviteCodeStatus(loginInfo.inviteId)
                        saveFormAddress(loginInfo.fromAddress)
                        getOdinAndHashValue()
                    }
                })
    }
}